import 'package:flutter/material.dart';
import 'package:hxdj/common/base_page/base_page.dart';
import 'package:amap_flutter_search/amap_flutter_search.dart';
import 'package:hxdj/common/components/my_alert.dart';
import 'package:hxdj/common/dio/dio_http.dart';
import 'package:hxdj/common/dio/my_api.dart';
import 'package:hxdj/common/my_global.dart';
import 'package:hxdj/home/address/select_address/address_model.dart';
import 'package:hxdj/home/address/select_address/select_address_viewmodel.dart';
import 'package:hxdj/login/user_model.dart';
import 'package:provider/provider.dart';

class EditAddressViewModel extends BaseViewModel {
  late AddressModel addressModel;

  late AMapPoiModel tempPoiModel;
  late int sex = 1; //性别 1男 2女

  bool isDefault = false;

  //是否可以保存
  bool isSave = false;

  TextEditingController nameController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController addressController = TextEditingController();
  TextEditingController doorController = TextEditingController(); //门牌号

  //选择性别
  void selectSex(int x) {
    sex = x;
    notifyListeners();
  }

  //设置默认地址
  void setDefault() {
    isDefault = !isDefault;
    notifyListeners();
  }

  //设置不可以保存了
  void setIsSave(bool isTempSave) {
    isSave = isTempSave;
    notifyListeners();
  }

  //选择了服务地址
  void selectAddress(AMapPoiModel poiModel) {
    addressController.text = poiModel.address ?? "";
    tempPoiModel = poiModel;
    // 请求成功后, 更新页面.
    notifyListeners();
  }

  //保存地址
  Future<void> saveAddress() async {
    Map<String, dynamic> params = {
      "default_status": isDefault ? 1 : 0,
      "mobile": phoneController.text,
      "contacts": nameController.text,
      "address": addressController.text,
      "sex": sex,
      "address_detail": doorController.text,
      "lon": tempPoiModel.longitude,
      "lat": tempPoiModel.latitude,
      "adds_province": tempPoiModel.province,
      "adds_city": tempPoiModel.city,
      "adds_area": tempPoiModel.district,
    };
    if (addressModel.id != null) {
      params['id'] = addressModel.id;
    }

    Map<String, dynamic> resultMap =
        await DioHttpManager()
        .request(MyApi.saveMemberAdds, method: DioHttpManager.post, data: params, isLoading: true);
    // 请求成功后, 更新页面.
    if (resultMap['code'] == 0) {
      Navigator.pop(context);
      SelectAddressViewModel viewModel = context.read<SelectAddressViewModel>();
      viewModel.requestData();
    }
  }

  //删除地址
  deleteAddress(String addressId) {
    MyAlertManager.showAlert(AlertType.iosMode, context, "您确定要删除地址吗？", "", onSure: () async {
      Map<String, dynamic> resultMap =
          await DioHttpManager()
          .request("del_member_adds", method: DioHttpManager.post, data: {"adds_id": addressId}, isLoading: true);
      // 请求成功后, 更新页面.
      if (resultMap['code'] == 0) {
        Navigator.pop(context);
        SelectAddressViewModel viewModel = context.read<SelectAddressViewModel>();
        viewModel.requestData();
      }
    });
  }

  Future<void> getAddressDetail(String addressId) async {
    clean();
    setState(ViewState.loading);
    addressModel = AddressModel();
    if (addressId.isNotEmpty) {
      await Future.delayed(const Duration(milliseconds: 300));
      // 去请求服务器数据.
      Map<String, dynamic> resultMap =
          await DioHttpManager()
          .request(MyApi.memberAddsInfo, method: DioHttpManager.post, data: {"adds_id": addressId});
      // 请求成功后, 更新页面.
      if (resultMap['code'] == 0) {
        addressModel = AddressModel.fromMap(resultMap["data"]);
      }

      //如果是编辑地址, 名字直接赋值过去, 还有性别信息
      nameController.text = addressModel.contacts ?? "";

      //如果是新增地址, 性别信息默认选中
      //也获取当前用户信息的性别
      MyGlobalViewModel globalViewModel = Provider.of<MyGlobalViewModel>(context, listen: false);
      UserModel? userModel = globalViewModel.userModel;
      sex = addressModel.sex ?? userModel?.sex ?? 1;
      isDefault = addressModel.defaultStatus == 1;
      //如果是编辑地址, 手机号码直接传过去
      phoneController.text = addressModel.mobile ?? "";

      addressController.text = addressModel.address ?? "";

      doorController.text = addressModel.addressDetail ?? "";


      //如果是编辑的 给 tempPoiModel
      tempPoiModel = AMapPoiModel(
          longitude: addressModel.lon.toString(),
          latitude: addressModel.lat.toString(),
          province: addressModel.addsProvince ?? "",
          district: addressModel.addsArea ?? "",
          city: addressModel.addsCity ?? "");
    }
    
    setState(ViewState.normal);

    checkInput();
  }

  clean() {
    nameController.clear();
    phoneController.clear();
    addressController.clear();
    doorController.clear();
  }

  //检测用户输入的信息,  控制保存按钮的状态
  checkInput() {
    if (nameController.text.isNotEmpty &&
        phoneController.text.isNotEmpty &&
        addressController.text.isNotEmpty &&
        doorController.text.isNotEmpty) {
      setIsSave(true);
    } else {
      setIsSave(false);
    }
  }
}
